package com.hljcert.data.service.system.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hljcert.data.service.common.config.BusinessException;
import com.hljcert.data.service.common.config.StatusEnum;
import com.hljcert.data.service.system.dto.SysRoleDTO;
import com.hljcert.data.service.system.dto.SysRoleQueryDTO;
import com.hljcert.data.service.system.entity.SysRole;
import com.hljcert.data.service.system.mapper.SysRoleMapper;
import com.hljcert.data.service.system.mapper.SysUserRoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    public void add(SysRoleDTO dto) {
        SysRole sysRole = this.sysRoleMapper.selectByRoleCode(dto.getRoleCode());
        if (sysRole != null) {
            throw new BusinessException(StatusEnum.EXISTS_DATA, "角色已存在");
        }
        SysRole entity = new SysRole();
        BeanUtils.copyProperties(dto, entity);
        entity.setId(IdUtil.getSnowflakeNextIdStr());
        sysRoleMapper.insert(entity);
    }

    public void update(SysRoleDTO dto){
        SysRole entity = new SysRole();
        BeanUtils.copyProperties(dto, entity);
        sysRoleMapper.updateById(entity);
    }

    public void delete(String id) {
        if (sysUserRoleMapper.selectCountByRoleId(id) > 0) {
            throw new BusinessException(StatusEnum.FAIL, "该角色下有用户，请先删除用户绑定");
        }
        sysRoleMapper.deleteById(id);
    }

    public SysRole getById(String id) {
        return sysRoleMapper.selectById(id);
    }

    // 分页查询
    public IPage<SysRole> getPageList(SysRoleQueryDTO params) {
        IPage<SysRole> page = Page.of(params.getPageNo() , params.getPageSize());
        return this.sysRoleMapper.selectPageList(page, params);
    }
}
